package com.oreilly.ez.account;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.Options;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AviatorUtil {


    public static Object calc(String express, Params params){

//创建一个求值器实例，应当尽量复用该实例。
//        AviatorEvaluatorInstance instance =  AviatorEvaluator.getInstance();
////设置自定义选项
//        instance.setOption(Options.TRACE_EVAL, true);
        AviatorEvaluator.setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL, true);
        AviatorEvaluator.setOption(Options.TRACE_EVAL, true);
        Expression expression = AviatorEvaluator.compile(express);
//正常使用

//        instance.compile(express);
        Map<String, Object> map = new HashMap<>();
        if(params != null){

            List<FelEntry> entryList = params.getEntryList();
            if(entryList !=null && entryList.size()>0){
                for (FelEntry felEntry : entryList) {

                    map.put(felEntry.getKey(), new BigDecimal(String.valueOf(felEntry.getVal())));
                }
            }
        }

        System.out.println("params = " + map);
//        return AviatorEvaluator.execute(express, map);
       return expression.execute( map);

    }

}
